package com.gyms.fragment;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

import com.classic.okhttp.beans.HVVenueBean;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.activity.CollectionActivity;
import com.gyms.activity.GymDetailActivity;
import com.gyms.adapter.MyGymAdapter;
import com.gyms.base.BaseFragment;
import com.gyms.constant.Constants;
import com.gyms.manager.LocationManger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import constant.EventConstant;
import myInterface.OnItemClickLitener;
import refresh.PtrClassicFrameLayout;
import refresh.PtrDefaultHandler;
import refresh.PtrFrameLayout;
import refresh.PtrHandler;
import utils.StringUtils;
import weight.CommonEmptyView;
import weight.UiEvent;
import weight.head_foot_recyclerView.EndlessRecyclerOnScrollListener;
import weight.head_foot_recyclerView.HeaderAndFooterRecyclerViewAdapter;
import weight.head_foot_recyclerView.LoadingFooter;
import weight.head_foot_recyclerView.RecyclerViewStateUtils;

/**
 * 收藏的场馆 yjl
 */
public class GymCollectFragment extends BaseFragment implements CommonEmptyView.UpdateClick {
    @BindView(R.id.bg_refresh_layout)
    RecyclerView bgRefreshLayout;
    @BindView(R.id.pf_collect)
    PtrClassicFrameLayout mPtrGymCollect;
    @BindView(R.id.search_empty)
    CommonEmptyView searchEmpty;
    private CollectionActivity mActivity;
    /* ----------   所有场馆 -------*/
    private List<HVVenueBean> mHVVenueBeans = new ArrayList<>();
    /* ----------   全部场馆 -------*/
    private MyGymAdapter mAllGymAdapter;
    private LocationManger mLocationManger;//定位的manger
    private static final int S_SPACE_RES=R.layout.view_space;
    //刷新 与加载更多
    private boolean isCanLoadMore=true;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_base_xrecycler;
    }

    @Override
    protected void initView() {
        createLoadingView("加载中", true);
        mActivity=(CollectionActivity)getActivity();
        searchEmpty.setUpDateClick(this);
        initAdapter();
        mLocationManger= LocationManger.getInstance(getActivity());
    }

    private void initAdapter() {
        DisplayMetrics dm = new DisplayMetrics();
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        bgRefreshLayout.setLayoutManager(layoutManager);
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        mAllGymAdapter = new MyGymAdapter(mContext,dm.widthPixels,mHVVenueBeans,mActivity.loadingView,searchEmpty,bgRefreshLayout);
        mAllGymAdapter.setHeadRes(S_SPACE_RES);
        HeaderAndFooterRecyclerViewAdapter headerAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mAllGymAdapter);
        bgRefreshLayout.setAdapter(headerAndFooterRecyclerViewAdapter);
        bgRefreshLayout.addOnScrollListener(mOnScrollListener);
    }

    @Override
    protected void initListener() {
        //注册EventBus
        EventBus.getDefault().register(this);
        mAllGymAdapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                HVVenueBean mHVVenueBean=mHVVenueBeans.get(position);
                boolean isVenueOnline=mHVVenueBean.getVenueState();//场馆是否上架
                if(isVenueOnline){//上架才能点击
                    Bundle mBundle = new Bundle();
                    mBundle.putString(Constants.FLAG_INTENT_VENUEID, mHVVenueBean.getVenueId());
                    startActivity(GymDetailActivity.class, mBundle, false);
                }

            }
        });
        mPtrGymCollect.disableWhenHorizontalMove(true);//解决和ViewPager的冲突
        mPtrGymCollect.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                reFlash();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
    }

    @Override
    protected void processLogic() {
        mActivity.loadingView.show();
        getVenueList();
    }

    /**
     * 获取我的场馆列表
     */
    private void getVenueList() {
        IUserService.getMyCollectionVenueList(getActivity(), mPageIndex, PAGESIZE, 1, mLocationManger.longitude, mLocationManger.latitude, true, new ObjectCallback<ArrayList<HVVenueBean>>() {

            @Override
            public void onSuccess(ArrayList<HVVenueBean> response, String message) {
                mActivity.dialogDis(bgRefreshLayout,searchEmpty);
                if (mIsRefreshOrLoadMore == 1) {
                    RecyclerViewStateUtils.setFooterViewState(bgRefreshLayout, LoadingFooter.State.Normal);
                } else if (mIsRefreshOrLoadMore == 0) {
                    mPtrGymCollect.refreshComplete();
                }
                if (null != response && response.size() != 0) {
                    if (mIsRefreshOrLoadMore == 0) {//刷新清空数据源
                        mHVVenueBeans.clear();
                    }
                    mAllGymAdapter.setData(response);
                } else {
                    if (mIsRefreshOrLoadMore == 0) {
                        showEmptyView(bgRefreshLayout,searchEmpty, 1);
                    } else {
                        isCanLoadMore=false;
                        doLoadMoreErro("没有更多的数据了");
                    }
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVVenueBean> response, String errorMessage) {
                mActivity.dialogDis();
                showEmptyView(bgRefreshLayout,searchEmpty, code);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                mActivity.dialogDis();
                showEmptyView(bgRefreshLayout,searchEmpty, Constants.NO_NET);
            }
        });
    }

    /**
     * 加载更多出现错误的处理
     */
    private void doLoadMoreErro(String erroStr) {
        if (mIsRefreshOrLoadMore == 1) {
            mPageIndex--;
            if(bgRefreshLayout!=null) {
//                bgRefreshLayout.setNoMoreData();
                RecyclerViewStateUtils.setFooterViewState(bgRefreshLayout, LoadingFooter.State.TheEnd);

            }
            ToastUtil.showToast(mContext, erroStr);
        } else if (mIsRefreshOrLoadMore == 0) {
            if(bgRefreshLayout!=null) {
                mPtrGymCollect.refreshComplete();
            }
        }
    }

    @Override
    public void onUpdateClick() {
        mActivity.loadingView.show();
        //刷新的时候将pageIndex始终为1
        reFlash();
    }

    private void reFlash() {
        isCanLoadMore=true;
        mPageIndex = 1;
        mIsRefreshOrLoadMore = 0;
        getVenueList();
    }

    /**
     * EventBus 接收事件
     *
     * @param uiEvent s
     */
    @Subscribe
    public void getName(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.FLAG_REFRESH_MY_VENUE)) {
            reFlash();
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
    }

    /**
     * 上拉加载监听
     */

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if(StringUtils.isNull(bgRefreshLayout)){
                return;
            }
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(bgRefreshLayout);
            if(state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                return;
            }

            if (isCanLoadMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), bgRefreshLayout, PAGESIZE, LoadingFooter.State.Loading, null);
                doLoadMore();
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), bgRefreshLayout, PAGESIZE, LoadingFooter.State.TheEnd, null);
            }
        }
    };

    private void doLoadMore() {
        mPageIndex++;
        mIsRefreshOrLoadMore = 1;
        getVenueList();
    }
}
